<template>
  <div class="task-monitor">
    <el-card class="page-card">
      <template #header>
        <div class="card-header">
          <span>异步任务监控</span>
          <div class="header-actions">
            <el-button type="primary" size="small" @click="refreshTasks">刷新</el-button>
            <el-button type="warning" size="small" @click="handleBatchCancel">批量取消</el-button>
          </div>
        </div>
      </template>

      <!-- 任务统计 -->
      <div class="task-stats">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-card shadow="hover" class="stat-card accent-primary">
              <div class="stat-item">
                <div class="stat-value running">{{ taskStats.running }}</div>
                <div class="stat-label">运行中</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stat-card accent-success">
              <div class="stat-item">
                <div class="stat-value finished">{{ taskStats.finished }}</div>
                <div class="stat-label">已完成</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stat-card accent-danger">
              <div class="stat-item">
                <div class="stat-value failed">{{ taskStats.failed }}</div>
                <div class="stat-label">失败</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stat-card accent-info">
              <div class="stat-item">
                <div class="stat-value total">{{ taskStats.total }}</div>
                <div class="stat-label">总任务数</div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 筛选和搜索 -->
      <div class="filter-section card-section">
        <div class="section-header">
          <h3 class="section-title">筛选条件</h3>
        </div>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-select v-model="filters.state" placeholder="任务状态" clearable>
              <el-option label="全部" value="" />
              <el-option label="运行中" value="RUNNING" />
              <el-option label="已完成" value="FINISHED" />
              <el-option label="失败" value="FAILED" />
              <el-option label="已取消" value="CANCELED" />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-input
              v-model="filters.search"
              placeholder="搜索任务名称"
              clearable
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-col>
          <el-col :span="6">
            <el-date-picker
              v-model="filters.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-col>
          <el-col :span="6">
            <el-button type="primary" @click="applyFilters">筛选</el-button>
            <el-button @click="clearFilters">清除</el-button>
          </el-col>
        </el-row>
      </div>
      
      <el-card class="table-card">
        <template #header>
          <div class="section-header">
            <h3 class="section-title">任务列表</h3>
          </div>
        </template>
        <el-table :data="filteredTasks" style="width: 100%" v-loading="loading">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="query_id" label="查询ID" width="120" />
          <el-table-column prop="task_name" label="任务名称" />
          <el-table-column prop="state" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStateType(row.state)" size="small">
                {{ getStateText(row.state) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="create_time" label="创建时间" width="180">
            <template #default="{ row }">
              {{ formatTime(row.create_time) }}
            </template>
          </el-table-column>
          <el-table-column prop="finish_time" label="完成时间" width="180">
            <template #default="{ row }">
              {{ formatTime(row.finish_time) }}
            </template>
          </el-table-column>
          <el-table-column prop="progress" label="进度" width="100">
            <template #default="{ row }">
              <el-progress
                v-if="row.state === 'RUNNING' && row.progress"
                :percentage="parseInt(row.progress)"
                :stroke-width="8"
              />
              <span v-else-if="row.state === 'FINISHED'">100%</span>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column prop="error_message" label="错误摘要" min-width="240">
            <template #default="{ row }">
              <span v-if="row.state === 'FAILED' && row.error_message">
                <el-tooltip :content="row.error_message" placement="top" :disabled="(row.error_message || '').length <= 60">
                  <span>{{ summarizeError(row.error_message) }}</span>
                </el-tooltip>
              </span>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="140" fixed="right">
            <template #default="{ row }">
              <el-button type="text" size="small" @click="viewDetail(row)">详情</el-button>
              <el-button v-if="row.state === 'RUNNING'" type="text" size="small" @click="cancelTask(row)">取消</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 任务详情对话框 -->
    <TaskDetail
      v-model:visible="detailVisible"
      :task="selectedTask ? {
        queryId: selectedTask.query_id || '',
        taskName: selectedTask.task_name || '',
        createTime: selectedTask.create_time || '',
        finishTime: selectedTask.finish_time,
        state: selectedTask.state,
        catalog: selectedTask.catalog || '',
        database: selectedTask.database_name || '',
        definition: selectedTask.definition || '',
        expireTime: undefined,
        errorCode: selectedTask.error_code,
        errorMessage: selectedTask.error_message,
        extraMessage: selectedTask.extra_message,
        properties: selectedTask.properties,
        progress: undefined
      } : null"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import TaskDetail from '@/components/TaskDetail.vue'
import { taskApi } from '@/api/task'
import type { TaskRun } from '@/types'

// 响应式数据
const tasks = ref<TaskRun[]>([])
const loading = ref(false)
const detailVisible = ref(false)
const selectedTask = ref<TaskRun | null>(null)

// 筛选条件
const filters = reactive({
  state: '',
  search: '',
  dateRange: [] as string[]
})

// 分页
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 任务统计
const taskStats = computed(() => {
  const stats = {
    running: 0,
    finished: 0,
    failed: 0,
    total: tasks.value.length
  }
  
  tasks.value.forEach(task => {
    switch (task.state) {
      case 'RUNNING':
        stats.running++
        break
      case 'FINISHED':
        stats.finished++
        break
      case 'FAILED':
        stats.failed++
        break
    }
  })
  
  return stats
})

// 筛选后的任务
const filteredTasks = computed(() => {
  let result = tasks.value
  
  if (filters.state) {
    result = result.filter(task => task.state === filters.state)
  }
  
  if (filters.search) {
    const searchLower = filters.search.toLowerCase()
    result = result.filter(task => 
      task.task_name?.toLowerCase().includes(searchLower) ||
      task.query_id?.toLowerCase().includes(searchLower)
    )
  }
  
  if (filters.dateRange && filters.dateRange.length === 2) {
    const [startDate, endDate] = filters.dateRange
    result = result.filter(task => {
      const createDate = task.create_time?.split('T')[0]
      return createDate && createDate >= startDate && createDate <= endDate
    })
  }
  
  return result
})

const loadTasks = async () => {
  loading.value = true
  try {
    const response = await taskApi.getTasks({
      page: pagination.page,
      size: pagination.size,
      ...filters
    })
    tasks.value = response.data.items
    pagination.total = response.data.pagination.total
  } catch (error) {
    console.error('Failed to load tasks:', error)
    ElMessage.error('加载任务列表失败')
  } finally {
    loading.value = false
  }
}

const refreshTasks = () => {
  loadTasks()
}

const applyFilters = () => {
  pagination.page = 1
  loadTasks()
}

const clearFilters = () => {
  filters.state = ''
  filters.search = ''
  filters.dateRange = []
  pagination.page = 1
  loadTasks()
}

const viewDetail = (task: TaskRun) => {
  selectedTask.value = task
  detailVisible.value = true
}

const cancelTask = async (task: TaskRun) => {
  try {
    await ElMessageBox.confirm(
      `确定要取消任务 "${task.task_name}" 吗？`,
      '确认取消',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await taskApi.cancelTask(task.id)
    ElMessage.success('任务取消成功')
    loadTasks()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Cancel task failed:', error)
      ElMessage.error('取消任务失败')
    }
  }
}

// 去除重试相关逻辑

const handleBatchCancel = () => {
  ElMessage.info('批量取消功能开发中...')
}

const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.page = 1
  loadTasks()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  loadTasks()
}

const getStateType = (state: string): string => {
  const types: Record<string, string> = {
    'RUNNING': 'primary',
    'FINISHED': 'success',
    'FAILED': 'danger',
    'CANCELED': 'info'
  }
  return types[state] || 'info'
}

const getStateText = (state: string): string => {
  const texts: Record<string, string> = {
    'RUNNING': '运行中',
    'FINISHED': '已完成',
    'FAILED': '失败',
    'CANCELED': '已取消'
  }
  return texts[state] || state
}

const formatTime = (time: string): string => {
  if (!time) return '-'
  return new Date(time).toLocaleString('zh-CN')
}

const summarizeError = (msg?: string): string => {
  if (!msg) return '-'
  const trimmed = msg.replace(/\s+/g, ' ').trim()
  return trimmed.length > 60 ? trimmed.slice(0, 60) + '…' : trimmed
}

onMounted(() => {
  loadTasks()
})
</script>

<style scoped>
.task-monitor { padding: 0; }
.page-card { background: linear-gradient(180deg, #ffffff 0%, #fafcfe 100%); border: 1px solid #eef2f6; border-radius: 12px; box-shadow: 0 4px 16px rgba(31,35,41,0.06); }
.card-header { display: flex; justify-content: space-between; align-items: center; padding-bottom: 6px; border-bottom: 1px dashed #eef2f6; }
.header-actions { display: flex; gap: 10px; }

.task-stats { margin-bottom: 20px; }
.stat-card { text-align: center; border-left: 4px solid var(--accent, #409EFF); background: linear-gradient(180deg, var(--accent-bg, #f0f7ff) 0%, #ffffff 40%); }
.stat-card.accent-primary { --accent:#409eff; --accent-bg:#f0f7ff; }
.stat-card.accent-success { --accent:#67C23A; --accent-bg:#ecfdf5; }
.stat-card.accent-danger { --accent:#F56C6C; --accent-bg:#feecec; }
.stat-card.accent-info { --accent:#909399; --accent-bg:#f3f4f6; }
.stat-item { padding: 20px; }
.stat-value { font-size: 24px; font-weight: 800; margin-bottom: 8px; }
.stat-value.running { color: #409EFF; }
.stat-value.finished { color: #67C23A; }
.stat-value.failed { color: #F56C6C; }
.stat-value.total { color: #909399; }
.stat-label { color: #606266; font-size: var(--font-subtitle); }

.card-section { background: linear-gradient(180deg, #ffffff 0%, #fafcfe 100%); border: 1px solid #eef2f6; border-radius: 12px; box-shadow: 0 4px 16px rgba(31,35,41,0.06); padding: 16px; margin-bottom: 16px; }
.section-header { display: flex; justify-content: space-between; align-items: center; padding-bottom: 6px; margin-bottom: 8px; border-bottom: 1px dashed #eef2f6; }
.section-title { margin: 0; font-size: var(--font-title); font-weight: 700; color: #1f2937; }

.table-card { margin-top: 8px; background: linear-gradient(180deg, #ffffff 0%, #fafcfe 100%); border: 1px solid #eef2f6; border-radius: 12px; box-shadow: 0 4px 16px rgba(31,35,41,0.06); }
.pagination-wrapper { margin-top: 20px; text-align: right; }
</style> 